<template>
  <div class="user-management">
    <t-card title="用户管理">
      <!-- 搜索表单 -->
      <t-form ref="form" :data="searchForm" @submit="onSearch">
        <t-row :gutter="[16, 16]">
          <t-col :span="6">
            <t-form-item label="用户名">
              <t-input v-model="searchForm.username" placeholder="请输入用户名" />
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="角色">
              <t-select v-model="searchForm.role" placeholder="请选择角色">
                <t-option value="admin" label="管理员" />
                <t-option value="user" label="普通用户" />
              </t-select>
            </t-form-item>
          </t-col>
          <t-col :span="12">
            <t-form-item>
              <t-space>
                <t-button theme="primary" type="submit">搜索</t-button>
                <t-button theme="default" @click="onReset">重置</t-button>
                <t-button theme="primary" @click="onAdd">新增用户</t-button>
              </t-space>
            </t-form-item>
          </t-col>
        </t-row>
      </t-form>

      <!-- 用户表格 -->
      <t-table
        :data="tableData"
        :columns="columns"
        :loading="loading"
        :pagination="pagination"
        @page-change="onPageChange"
      >
        <template #status="{ row }">
          <t-tag :theme="row.status === 'active' ? 'success' : 'danger'">
            {{ row.status === 'active' ? '启用' : '禁用' }}
          </t-tag>
        </template>
        <template #op="{ row }">
          <t-space>
            <t-button theme="primary" variant="text" @click="onEdit(row)">编辑</t-button>
            <t-button theme="danger" variant="text" @click="onDelete(row)">删除</t-button>
          </t-space>
        </template>
      </t-table>
    </t-card>

    <!-- 新增/编辑对话框 -->
    <t-dialog
      v-model:visible="dialogVisible"
      :header="dialogType === 'add' ? '新增用户' : '编辑用户'"
      :on-confirm="onDialogConfirm"
    >
      <t-form ref="dialogForm" :data="formData" :rules="rules">
        <t-form-item label="用户名" name="username">
          <t-input v-model="formData.username" placeholder="请输入用户名" />
        </t-form-item>
        <t-form-item label="密码" name="password" v-if="dialogType === 'add'">
          <t-input v-model="formData.password" type="password" placeholder="请输入密码" />
        </t-form-item>
        <t-form-item label="邮箱" name="email">
          <t-input v-model="formData.email" placeholder="请输入邮箱" />
        </t-form-item>
        <t-form-item label="角色" name="role">
          <t-select v-model="formData.role" placeholder="请选择角色">
            <t-option value="admin" label="管理员" />
            <t-option value="user" label="普通用户" />
          </t-select>
        </t-form-item>
        <t-form-item label="状态" name="status">
          <t-radio-group v-model="formData.status">
            <t-radio value="active">启用</t-radio>
            <t-radio value="inactive">禁用</t-radio>
          </t-radio-group>
        </t-form-item>
      </t-form>
    </t-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { MessagePlugin } from 'tdesign-vue-next'
import type { FormInstanceFunctions } from 'tdesign-vue-next'
import type { User, UserQuery, UserCreate, UserUpdate } from '@/api/user'
import { getUsers, createUser, updateUser, deleteUser } from '@/api/user'

// 搜索表单数据
const searchForm = reactive<UserQuery>({
  username: '',
  role: ''
})

// 表格数据
const loading = ref(false)
const tableData = ref<User[]>([])
const columns = [
  { colKey: 'username', title: '用户名', width: 120 },
  { colKey: 'email', title: '邮箱', width: 180 },
  { colKey: 'role', title: '角色', width: 100 },
  { colKey: 'status', title: '状态', width: 100 },
  { colKey: 'createdAt', title: '创建时间', width: 180 },
  { colKey: 'op', title: '操作', width: 160 }
]

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0
})

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const formData = reactive<UserCreate & { id?: number }>({
  username: '',
  password: '',
  email: '',
  role: 'user',
  status: 'active'
})

// 表单校验规则
const rules = {
  username: [{ required: true, message: '请输入用户名', type: 'error' }],
  password: [{ required: true, message: '请输入密码', type: 'error' }],
  email: [
    { required: true, message: '请输入邮箱', type: 'error' },
    { pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/, message: '请输入正确的邮箱格式', type: 'error' }
  ],
  role: [{ required: true, message: '请选择角色', type: 'error' }]
}

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    const { data, total } = await getUsers({
      page: pagination.current,
      pageSize: pagination.pageSize,
      ...searchForm
    })
    tableData.value = data
    pagination.total = total
  } catch (error) {
    MessagePlugin.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const onSearch = () => {
  pagination.current = 1
  loadData()
}

// 重置
const onReset = () => {
  searchForm.username = ''
  searchForm.role = ''
  pagination.current = 1
  loadData()
}

// 分页变化
const onPageChange = (curr: number) => {
  pagination.current = curr
  loadData()
}

// 新增用户
const onAdd = () => {
  dialogType.value = 'add'
  dialogVisible.value = true
  Object.assign(formData, {
    username: '',
    password: '',
    email: '',
    role: 'user',
    status: 'active'
  })
}

// 编辑用户
const onEdit = (row: User) => {
  dialogType.value = 'edit'
  dialogVisible.value = true
  Object.assign(formData, {
    id: row.id,
    username: row.username,
    email: row.email,
    role: row.role,
    status: row.status
  })
}

// 删除用户
const onDelete = async (row: User) => {
  try {
    await MessagePlugin.confirm({
      header: '确认删除',
      body: `确定要删除用户 ${row.username} 吗？`,
      confirmBtn: {
        theme: 'danger'
      }
    })
    await deleteUser(row.id)
    MessagePlugin.success('删除成功')
    loadData()
  } catch (error) {
    if (error !== 'cancel') {
      MessagePlugin.error('删除失败')
    }
  }
}

// 对话框确认
const onDialogConfirm = async () => {
  try {
    if (dialogType.value === 'add') {
      await createUser(formData as UserCreate)
      MessagePlugin.success('新增成功')
    } else {
      const { id, ...updateData } = formData
      await updateUser(id!, updateData as UserUpdate)
      MessagePlugin.success('编辑成功')
    }
    dialogVisible.value = false
    loadData()
  } catch (error) {
    MessagePlugin.error(dialogType.value === 'add' ? '新增失败' : '编辑失败')
  }
}

// 初始加载
loadData()
</script>

<style scoped>
.user-management {
  background-color: #fff;
  padding: 24px;
  border-radius: 4px;
}
</style> 